package com.taotao.slink.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import com.google.common.base.Preconditions;
import com.taotao.slink.mapper.DayVisitMapper;
import com.taotao.slink.model.entity.DayVisit;
import com.taotao.slink.service.DayVisitService;
import com.taotao.slink.service.VisitStatistics;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;

/**
 * <p>
 * 日访问量统计服务接口实现类
 * </p>
 *
 * @author youbeiwuhuan
 * @version V1.0
 * @since 2023-06-27 12:08:05
 */
@Slf4j
@Service
public class DayVisitServiceImpl implements DayVisitService {
    @Resource
    private DayVisitMapper dayVisitMapper;


    @Override
    public PageInfo<DayVisit> queryByPage(DayVisit param, int pageNum, int pageSize) {
        Preconditions.checkArgument(pageNum > 0);
        Preconditions.checkArgument(pageSize > 0);

        Page<DayVisit> page = dayVisitMapper.selectByPage(param, pageNum, pageSize);

        return new PageInfo<>(page);
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveVisitInfo(VisitStatistics.DayVisitInfo value) {
        Preconditions.checkArgument(null != value);

        LocalDateTime now = LocalDateTime.now();
        while (true) {
            DayVisit visit = dayVisitMapper.selectByCodeAndDay(value.getCode(), value.getDay());
            if (null == visit) {
                try {
                    visit = new DayVisit();
                    visit.setDay(value.getDay());
                    visit.setVisitCount(value.getCount());
                    visit.setShortLinkCode(value.getCode());
                    visit.setCreateTime(now);
                    visit.setUpdateTime(now);
                    dayVisitMapper.saveIgnoreNull(visit);
                } catch (DuplicateKeyException e) {
                    continue;
                }
            }

            int effectRows = dayVisitMapper.addVisitCount(value.getCode(), value.getDay(), value.getCount(), visit.getVersion(), now);
            if (effectRows > 0) {
                break;
            }

        }
    }


}
